<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>仿设计待办事项</title>
    <link rel="stylesheet" href="./font/iconfont.css">
    <link rel="stylesheet" href="./hw.css">
  </head>
  <body>
    <div class="container">
      <header>
        <h1>待办事项</h1>
        <p class="subtitle">简单高效地管理你的任务</p>
      </header>
      <div class="core-section">
        <div class="input-group">
          <input type="text" id="todoInput" placeholder="添加新的待办事项..." />
          <button id="addBtn">+ 添加</button>
        </div>

        <div class="filters">
          <button class="filter-btn active" data-filter="all">全部</button>
          <button class="filter-btn" data-filter="active">未完成</button>
          <button class="filter-btn" data-filter="completed">已完成</button>
        </div>

        <ul id="todoList"></ul>
      </div>

      <div class="stats" id="statsBar">0 个未完成，0 个总计</div>
    </div>

    <script>
      //类的设计
      class Todo {
        constructor(id, text, completed = false) {
          this.id = id;
          this.text = text;
          this.completed = completed;
          this.timestamp = Date.now();
        }
      }

      class TodoApp {
        //构造函数
        constructor() {
          this.todos = this.loadFromStorage();
          this.currentFilter = "all";
          this.init();
        }
        //类的初始化
        init() {
          this.todoInput = document.getElementById("todoInput");
          this.addBtn = document.getElementById("addBtn");
          this.todoList = document.getElementById("todoList");
          this.filterButtons = document.querySelectorAll(".filter-btn");
          this.statsBar = document.getElementById("statsBar");

          this.bindEvents();
          this.render();
        }

        bindEvents() {
          // 回车添加
          this.todoInput.addEventListener("keypress", (e) => {
            if (e.key === "Enter") {
              this.addTodo();
            }
          });

          // 按钮添加
          this.addBtn.addEventListener("click", () => {
            this.addTodo();
          });

          // 过滤按钮
          this.filterButtons.forEach((btn) => {
            btn.addEventListener("click", () => {
              this.filterButtons.forEach((b) => b.classList.remove("active"));
              btn.classList.add("active");
              this.currentFilter = btn.dataset.filter;
              this.render();
            });
          });
        }
        //添加一个任务
        addTodo() {
          const text = this.todoInput.value.trim();
          if (text === "") return;

          const newTodo = new Todo(Date.now(), text);
          this.todos.push(newTodo);
          this.saveToStorage();
          this.render();
          this.todoInput.value = "";
          this.todoInput.focus();
        }
        //勾选一个任务
        toggleTodo(id) {
          const todo = this.todos.find((t) => t.id === id);
          if (todo) {
            todo.completed = !todo.completed;
            this.saveToStorage();
            this.render();
          }
        }
        //删除一个任务
        deleteTodo(id) {
          const itemEl = document.querySelector(`[data-id="${id}"]`);
          if (itemEl) {
            itemEl.classList.add("leaving");
            setTimeout(() => {
              this.todos = this.todos.filter((t) => t.id !== id);
              this.saveToStorage();
              this.render();
            }, 300);
          }
        }
        //获得当前过滤状态
        getFilteredTodos() {
          switch (this.currentFilter) {
            case "active":
              return this.todos.filter((t) => !t.completed);
            case "completed":
              return this.todos.filter((t) => t.completed);
            default:
              return this.todos;
          }
        }
        //重新渲染
        render() {
          const filtered = this.getFilteredTodos();
          if (filtered.length === 0) {
            this.todoList.innerHTML = '<div class="empty">暂无任务</div>';
          } else {
            this.todoList.innerHTML = "";
            filtered.forEach((todo) => {
              const li = document.createElement("li");
              li.className = `todo-item ${todo.completed ? "completed" : ""}`;
              li.dataset.id = todo.id;

              li.innerHTML = `
              <input type="checkbox" class="todo-checkbox" ${
                todo.completed ? "checked" : ""
              }>
              <span class="todo-text">${this.escapeHtml(todo.text)}</span>
              <button class="iconfont icon-ic_crash delete-btn"></button>
            `;

              li.querySelector(".todo-checkbox").addEventListener(
                "change",
                () => {
                  this.toggleTodo(todo.id);
                }
              );
              li.querySelector(".delete-btn").addEventListener("click", () => {
                this.deleteTodo(todo.id);
              });

              this.todoList.appendChild(li);
            });
          }

          // 更新底部统计
          const total = this.todos.length;
          const active = this.todos.filter((t) => !t.completed).length;
          this.statsBar.textContent = `${active} 个未完成，${total} 个总计`;
        }
        //转义html防止被xss攻击
        escapeHtml(text) {
          const div = document.createElement("div");
          div.textContent = text;
          return div.innerHTML;
        }
        //保存存入和删除的数据
        saveToStorage() {
          localStorage.setItem("todos", JSON.stringify(this.todos));
        }
        //刷新页面后，加载过往的数据
        loadFromStorage() {
          const data = localStorage.getItem("todos");
          return data
            ? JSON.parse(data).map((t) => Object.assign(new Todo(), t))
            : [];
        }
      }

      new TodoApp();
    </script>
  </body>
</html>
